package com.nowcoder.community.service;

import com.nowcoder.community.dao.MessageMapper;
import com.nowcoder.community.entity.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.util.HtmlUtils;

import java.util.List;

@Service
public class MessageService {

    @Autowired
    private MessageMapper messageMapper;

    // 根据userId查询会话列表（即最新私信列表）
    public List<Message> findConversations(int userId, int limit, int offset) {
        return messageMapper.selectConversations(userId, limit, offset);
    }

    // 查询会话总数
    public int findConversationCount(int userId) {
        return messageMapper.selectConversationCount(userId);
    }

    // 根据 conversationId 查询会话的所有私信
    public List<Message> findLetters(String conversationId, int limit, int offset) {
        return messageMapper.selectLetters(conversationId, limit, offset);
    }

    // 根据conversationId查询私信数量
    public int findLetterCount(String conversationId) {
        return messageMapper.selectLetterCount(conversationId);
    }

    // 根据 userId 和 conversationId查询未读私信数量，如果conversationId为空则查询userId对应的用户的所有未读私信
    public int findLetterUnreadCount(int userId, String conversationId) {
        return messageMapper.selectLetterUnreadCount(userId, conversationId);
    }

    // 新增消息
    public int addMessage(Message message) {
        message.setContent(HtmlUtils.htmlEscape(message.getContent()));
        return messageMapper.insertMessage(message);
    }

    // 批量删除消息
    public int deleteMessage(List<Integer> ids) {
        if (!ids.isEmpty()) {
            return messageMapper.updateStatus(ids, 2);
        }
        return 0;
    }

    // 批量设置消息为已读
    public int readMessage(List<Integer> ids) {
        if (!ids.isEmpty()) {
            return messageMapper.updateStatus(ids, 1);
        }
        return 0;
    }

    // 查询用户的未读通知数，如果topic为空则查询所有类别
    public int findNoticeUnreadCount(int userId, String topic) {
        return messageMapper.selectNoticeUnreadCount(userId, topic);
    }

    // 查询用户最新未读通知
    public Message findLatestNotice(int userId, String topic) {
        List<Message> messages = messageMapper.selectNotices(userId, topic, 1, 0);
        return messages.isEmpty() ? null : messages.get(0);
    }

    // 查询用户某类别的所有通知
    public List<Message> findNotices(int userId, String topic, int limit, int offset) {
        return messageMapper.selectNotices(userId, topic, limit, offset);
    }

    // 查询用户某类别的所有通知数
    public int findNoticeCount(int userId, String topic) {
        return messageMapper.selectNoticeCount(userId, topic);
    }

}
